package cn.risebd.wechat.pay.controller;

import java.io.IOException;

import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;

import cn.risebd.common.util.UUIDHexGenerator;
import cn.risebd.wechat.pay.support.WepaySupport;
import cn.risebd.wepay.model.pay.JsPayResponse;

@RestController
@RequestMapping("/pays/")
public class Pays {

	private static final Logger logger = LoggerFactory.getLogger(Pays.class);

	@Autowired
	private WepaySupport wepaySupport;

	/**
	 * 二维码支付
	 * 
	 * @param orderNumber
	 *            商户订单号
	 */
	@RequestMapping(value = "/qrpay")
	public void qrPay(HttpServletResponse response) {
		String orderNumber = UUIDHexGenerator.generate();
		orderNumber = orderNumber.substring(4, orderNumber.length());

		try {
			String qrUrl = wepaySupport.qrPay(orderNumber, (int) (0.01 * 100));
			response.sendRedirect(qrUrl);
		} catch (IOException e) {
			logger.error("failed to qr pay(orderNumber={}), cause: {}", orderNumber, e.getMessage());
		}
	}

	/**
	 * 二维码支付
	 * 
	 * @param orderNumber
	 *            商户订单号
	 */
	@RequestMapping(value = "/qrpay/{payAmount}")
	public void qrPay(@PathVariable(value = "payAmount") Integer payAmount, HttpServletResponse response) {
		String orderNumber = UUIDHexGenerator.generate();
		orderNumber = orderNumber.substring(4, orderNumber.length());

		try {
			String qrUrl = wepaySupport.qrPay(orderNumber, payAmount * 100);
			response.sendRedirect(qrUrl);
		} catch (IOException e) {
			logger.error("failed to qr pay(orderNumber={}), cause: {}", orderNumber, e.getMessage());
		}
	}

	@RequestMapping(value = "/jspay", produces = { "text/json; charset=UTF-8" })
	@ResponseBody
	public String jsPay(String openId) {
		String orderNumber = UUIDHexGenerator.generate();
		orderNumber = orderNumber.substring(4, orderNumber.length());
		logger.info("orderNumber={},openId={}", orderNumber, openId);
		JsPayResponse response = wepaySupport.jsPay(orderNumber, openId);
		String result = JSON.toJSONString(response);
		logger.info("result={}", result);
		return result;
	}

}
